# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

import logging
from datetime import datetime
import time

from pylons import tmpl_context as c, request, url
from pylons.i18n import lazy_ugettext as _
from pylons.controllers.util import redirect

from repoze.what.plugins.pylonshq import ControllerProtector
from repoze.what.predicates import not_anonymous

from chowa.lib.base import BaseController, render, Session
from chowa.model.auth import User
from chowa.model.social import Comment

log = logging.getLogger(__name__)

@ControllerProtector(not_anonymous())
class CommentsController(BaseController):
    def view(self, id):
        query = Session.query(Comment).filter_by(topic_id=id)
        c.comments = query.order_by('created').all()
        c.topic_id = id
        c.time = int(time.time())
        return render('/social/comments.html')
    
    def __before__(self):
        identity = request.environ.get('repoze.who.identity')
        self.user = identity.get('user')

    def add(self, id):
        if request.method == 'POST':
            text = request.POST.get('text')[:1000]
            comment = Comment(text=text,
                              user_id=self.user.id,
                              topic_id=id,
                              created=datetime.now())
            Session.add(comment)
            Session.commit()
        return redirect(url.current(action='view'))
    
    def comment(self, id):
        comment = Session.query(Comment).get(id)
        return render('/social/comment.html',
                      extra_vars={'comment': comment}).strip()

    def reply(self, id):
        if request.method == 'POST':
            text = request.POST.get('text')[:1000]
            comment = Comment(text=text,
                              user_id=self.user.id,
                              reply_to=id,
                              created=datetime.now())
            Session.add(comment)
            Session.commit()
        return redirect(url.current(action='comment'))

